const Logger = require('../util/baseUtil/LogUtil')

//格式化ip
function RealIp(req) {
    if (req.ip) {
        let ip1 = req.ip.replace(/:/g, '')
        let ip2 = ip1.replace(/f/g, '')
        return ip2;
    } else {
        return '';
    }
}

/**
 *
 * @param app
 * common log
 */

//对用户请求进行记录并且对异常用户进行拦截
module.exports = function (app) {
    app.use((req, res, next) => {
        let parseDate = {}
        //获取请求协议
        let protocol = req.protocol ? req.protocol : '';
        //获取请求ip
        let ip = RealIp(req);
        //获取主机名
        let hostname = req.hostname ? req.hostname : '';
        //请求方法
        let method = req.method ? req.method : '';
        //收集请求头
        let headers = req.headers ? req.headers : '';
        // 收集body
        let body = req.body ? req.body : '';
        // 收集query
        let query = req.query ? req.query : '';
        //请求路径
        let url = req.originalUrl ? req.query : '';
        parseDate.protocol = protocol
        parseDate.ip = ip
        parseDate.hostname = hostname
        parseDate.method = method
        parseDate.headers = headers
        // parseDate.cookies = cookies
        // parseDate.cookie = cookie
        parseDate.body = body
        parseDate.query = query
        parseDate.url = url
        if (req.session) {
            parseDate.session = req.session
            if (req.session.user) {
                parseDate.user = req.session.user
            }
        }
        // Logger.info('request_info', parseDate, true)
        Logger.info('record_info',parseDate)
        next()
    })
}
